package mysql

import (
	"backend/app/model"
	"fmt"
)

func CheckMenuIsExist(menuId int32) (bool, error) {
	sqlStr := `select count(menu_id) from menu where menu_id=?`
	var count int
	err := Db.Get(&count, sqlStr, menuId)
	if err != nil {
		fmt.Printf("scan failed, err: %v\n", err)
		return false, err
	}
	if count > 0 {
		return true, nil
	}
	return false, nil
}

func InsertMenuItem(menuItem *model.Menu) error {
	sqlStr := "insert into menu(name, redirect, component, path, meta, parent_id) values(?,?,?,?,?,?)"
	_, err := Db.Exec(sqlStr, menuItem.Name, menuItem.Redirect, menuItem.Component, menuItem.Path, menuItem.Meta, menuItem.ParentId)
	return err
}

func UpdateMenuItem(menuItem *model.Menu) error {
	sqlStr := `update menu set name=?, redirect=?, component=?, path=?, meta=?, parent_id=? where menu_id=?`
	_, err := Db.Exec(sqlStr, menuItem.Name, menuItem.Redirect, menuItem.Component, menuItem.Path, menuItem.Meta, menuItem.ParentId, menuItem.MenuId)
	return err
}

func DeleteMenuItem(menuId int32) error {
	sqlStr := `delete from menum where menu_id=?`
	_, err := Db.Exec(sqlStr, menuId)
	return err
}

func QueryMenuItemByParentId(parentId int32) ([]model.Menu, error) {
	sqlStr := `select menu_id, name, path, component, redirect, meta from menu where parent_id=?`
	var menuItems []model.Menu
	err := Db.Select(&menuItems, sqlStr, parentId)
	return menuItems, err
}
